﻿using MCUPackage;
using MCUPackage.DesignEditor;
using MCUPackage.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace SxPackages.STC8.Models
{
	[Serializable]
	class AllUartOptions
	{
		/// <summary>
		/// 串口配置结合
		/// </summary>
		[Browsable(false),
		JsonIgnore]
		public USARTOptionBase[] All { get; private set; }

		[Category("串口配置"),
		DisplayName("串口1"),
		TypeConverter(typeof(PropertySorter))]
		public USART1Options USART1 { get; private set; }

		[Category("串口配置"),
		DisplayName("串口2"),
		TypeConverter(typeof(PropertySorter))]
		public USART2Options USART2 { get; private set; }

		public AllUartOptions(STC8HUSOP20 aParent)
		{
			this.USART1 = new USART1Options(aParent);
			this.USART2 = new USART2Options(aParent);
			All = new USARTOptionBase[] { this.USART1, this.USART2 };
		}

		/// <summary>
		/// 是否有启用的串口
		/// </summary>
		/// <returns></returns>
		public bool HasEnabled()
		{
			foreach (var uart in All)
			{
				if (uart.Enable)
				{
					return true;
				}
			}

			return false;
		}

		/// <summary>
		/// 是否有串口开启中断
		/// </summary>
		/// <returns></returns>
		public bool HasInterrupt()
		{
			foreach (var uart in All)
			{
				if (uart.Enable && uart.EnableTI)
				{
					return true;
				}
			}

			return false;
		}

		public bool AppendConfig(List<string[]> aLst)
		{
			if (!HasEnabled())
			{
				return false;
			}

			string name = "UART_Config";
			StringBuilder funcSb = new StringBuilder();
			funcSb.Append(TemplateHelper.GetFunctionCommit("串口模块初始化"));
			funcSb.AppendLine($"PRIVATE void {name}(void)").AppendLine("{");
			funcSb.AppendLine("\tCOMx_InitDefine attr;");

			Dictionary<string, List<string>> lst = new Dictionary<string, List<string>>();
			StringBuilder tmpSb = new StringBuilder();

			foreach (var uart in this.All)
			{
				var strs = uart.Generate(lst);
				if (strs != null)
				{
					tmpSb.AppendLine();
					tmpSb.Append(strs[0]);
				}
			}

			if (lst.Count > 0)
			{
				funcSb.AppendLine();
				funcSb.Append(GPIOOptions.GetGPIOConfigs(lst));
			}

			funcSb.Append(tmpSb);
			funcSb.AppendLine("}");

			aLst.Add(new string[] { funcSb.ToString(), $"{name}();" });

			return true;
		}
	}
}
